<template>
    <div class="wrapper">
        <div class="box" ref="box"></div>
        <div class="box2" ref="box2"></div>
    </div>
</template>
<script setup lang="ts"> 
import { ref, onMounted, onUnmounted } from 'vue'

// 1. 正确初始化ref变量，指定具体DOM类型并初始化为null
const box = ref<HTMLElement | null>(null)
const box2 = ref<HTMLElement | null>(null)
const handleScroll = () => {
  // 获取滚动距离
  const scrollTop = window.scrollY
  // 2. 使用可选链操作符(?.)避免空值访问错误
  if (box.value?.offsetTop && scrollTop >= box.value.offsetTop){
     //加上感叹号，表示box2.value不为null
    box2.value!.style.opacity='1'
  }else{
    box2.value!.style.opacity='0'
  }
}

onMounted(() => {
  // 组件挂载后才添加滚动监听（此时DOM已存在）
  window.addEventListener('scroll', handleScroll)
})
// 组件销毁时移除监听
onUnmounted(() => {
  // 组件卸载时移除监听，避免内存泄漏
  window.removeEventListener('scroll', handleScroll)
})
</script>
<style scoped>
.wrapper{
    height: 2000px;
}
.box{
    width: 100px;
    height: 100px;
    margin-top: 200px;
    background-color: red;
}
.box2{
    width: 100px;
    height: 100px;
    margin-top: 10px;
    margin-left: 100px;
    background-color: blue;
    opacity: 0;
    transition: all .3s;
}
</style>